<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学号导出工具 - 数智作业后台管理系统</title>
    <link rel="icon" href="/assets/ico/7favicon.png" type="image/png">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <script src="/js/api.js"></script>
    <style>
        .file-upload {
            border: 2px dashed #cbd5e1;
            transition: all 0.3s ease;
        }
        .file-upload:hover {
            border-color: #3b82f6;
        }
        .file-upload.dragover {
            border-color: #3b82f6;
            background-color: #f0f9ff; /* Light blue background on drag over */
        }
        .file-input {
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            width: 100%;
            cursor: pointer;
            opacity: 0;
            z-index: 2; /* Ensure input is clickable */
        }
        .fancy-input {
            display: block;
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid #e5e7eb;
            border-radius: 0.5rem;
            background-color: white;
            color: #1f2937;
            font-size: 1rem;
            line-height: 1.5;
            transition: all 0.3s ease;
            box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
        }
        .fancy-input:focus {
            border-color: #3b82f6;
            outline: none;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.3);
        }
        .fancy-button {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 0.75rem 1.75rem;
            background: linear-gradient(45deg, #3b82f6 0%, #4f46e5 100%);
            color: white;
            font-weight: 500;
            border-radius: 0.5rem;
            transition: all 0.3s ease;
            border: none;
            cursor: pointer;
            box-shadow: 0 4px 6px -1px rgba(37, 99, 235, 0.2), 0 2px 4px -1px rgba(37, 99, 235, 0.1);
        }
        .fancy-button:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 10px 15px -3px rgba(37, 99, 235, 0.2), 0 4px 6px -2px rgba(37, 99, 235, 0.1);
        }
        .fancy-button:active:not(:disabled) {
            transform: translateY(0);
        }
        .fancy-button:disabled {
            background: #9ca3af;
            cursor: not-allowed;
            box-shadow: none;
        }
        /* 新增侧边栏样式 */
        .side-panel {
            position: sticky;
            top: 2rem;
            max-height: calc(100vh - 4rem);
            overflow-y: auto;
            border-radius: 0.75rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            transition: all 0.3s ease;
            height: 100%;
            display: flex;
            flex-direction: column;
        }
        .status-indicator {
            transition: all 0.3s ease;
            margin-bottom: 1rem;
            border-radius: 0.5rem;
            overflow: hidden;
        }
        .status-indicator.active {
            border-left-width: 4px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
        }
        .progress-container {
            margin: 0.75rem 0;
        }
        .progress-bar-wrapper {
            height: 0.5rem;
            background-color: #e5e7eb;
            border-radius: 9999px;
            overflow: hidden;
        }
        .progress-bar {
            height: 100%;
            border-radius: 9999px;
            transition: width 0.5s ease, background-color 0.3s ease;
        }
        .info-box {
            border-radius: 0.5rem;
            border: 1px solid;
            padding: 0.75rem;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
        }
        .info-box.info {
            background-color: #eff6ff;
            border-color: #bfdbfe;
        }
        .info-box.success {
            background-color: #f0fdf4;
            border-color: #bbf7d0;
        }
        .info-box.warning {
            background-color: #fffbeb;
            border-color: #fef3c7;
        }
        .info-box.error {
            background-color: #fef2f2;
            border-color: #fecaca;
        }
        @keyframes pulse {
            0%, 100% {
                opacity: 1;
            }
            50% {
                opacity: 0.7;
            }
        }
        .pulse {
            animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
        }
        /* 恢复左侧表单区域样式，移除不需要的样式 */
        .toggle-checkbox:checked + .toggle-label {
            background-color: #dbeafe;
        }
        .toggle-label {
            width: 3rem;
            transition: background-color 0.3s ease;
        }
    </style>
</head>
<body class="bg-gray-50">
    <!-- 返回按钮 -->
    <div class="container mx-auto px-4 py-4">
        <a href="index.html" class="inline-flex items-center px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition duration-200">
            <i class="fas fa-arrow-left mr-2"></i>
            返回主页
        </a>
    </div>

    <div class="container mx-auto px-4 py-8">
        <!-- 面包屑导航和标题 -->
        <div class="flex items-center justify-between mb-8 max-w-5xl mx-auto">
            <div>
                <h1 class="text-2xl font-bold text-gray-800">学号导出工具</h1>
                <p class="text-gray-500 text-sm">上传学生明细Excel，自动分班导出学号</p>
            </div>
            <nav>
                <ol class="flex text-sm text-gray-500">
                    <li class="flex items-center">
                        <a href="index.html" class="text-blue-600 hover:text-blue-700">首页</a>
                        <i class="fas fa-chevron-right text-gray-400 mx-2 text-xs"></i>
                    </li>
                    <li class="flex items-center">
                        <a href="#" class="text-blue-600 hover:text-blue-700">系统工具</a>
                        <i class="fas fa-chevron-right text-gray-400 mx-2 text-xs"></i>
                    </li>
                    <li>
                        <span class="text-gray-600">学号导出工具</span>
                    </li>
                </ol>
            </nav>
        </div>

        <!-- 主要内容区 - 改为两栏布局 -->
        <div class="grid grid-cols-1 md:grid-cols-7 gap-6 max-w-6xl mx-auto">
            <!-- 左侧表单区域 -->
            <div class="md:col-span-4">
                <!-- 工具卡片 -->
                <div class="bg-white rounded-lg shadow-md p-6 md:p-8">
                    <h2 class="text-xl font-semibold text-gray-800 mb-6 text-center">学号导出工具配置</h2>
                    <form id="uploadForm" action="/downloadExcel" method="post" enctype="multipart/form-data" class="space-y-6">
                        <!-- Excel文件上传 -->
                        <div class="space-y-2">
                            <label class="block text-sm font-medium text-gray-700 flex items-center">
                                <i class="fas fa-file-excel text-green-500 mr-2"></i>
                                学生明细Excel文件
                            </label>
                            <!-- File Upload Area - Styled like file-merge.html -->
                            <div class="file-upload rounded-lg p-6 relative text-center cursor-pointer" id="fileDropArea">
                                <input type="file" name="file" id="fileUpload" class="file-input" accept=".xlsx,.xls" required>
                                <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-3"></i>
                                <p class="font-medium text-gray-600">点击或拖拽上传文件</p>
                                <p class="text-xs text-gray-500 mt-1">支持.xlsx, .xls格式</p>
                            </div>
                            <!-- File Info / Error Display -->
                            <div id="fileInfo" class="mt-2 text-sm text-gray-600 hidden flex items-center justify-between bg-gray-100 p-2 rounded">
                                <div class="flex items-center overflow-hidden">
                                    <i class="fas fa-check-circle text-green-500 mr-2 flex-shrink-0"></i>
                                    <span class="font-medium truncate" id="fileName"></span>
                                    <span class="text-gray-500 ml-2 flex-shrink-0" id="fileSize"></span>
                                </div>
                                <button type="button" id="removeFile" class="text-red-500 hover:text-red-700 ml-2 flex-shrink-0">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                            <div id="fileError" class="mt-2 text-sm text-red-600 hidden flex items-center">
                                <i class="fas fa-exclamation-circle mr-1"></i>
                                <span id="errorText"></span>
                            </div>
                        </div>

                        <!-- 学校名称输入 -->
                        <div class="space-y-2">
                            <label for="schoolName" class="block text-sm font-medium text-gray-700 flex items-center">
                                <i class="fas fa-school text-blue-500 mr-2"></i>
                                学校名称 (用于文件名和模板)
                            </label>
                            <input type="text" id="schoolName" name="replacementText" placeholder="请输入学校名称" class="fancy-input" required>
                        </div>

                        <!-- PDF Export Option -->
                        <div class="flex items-center space-x-2">
                            <input type="checkbox" id="includePdf" name="includePdf" value="true" class="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500">
                            <label for="includePdf" class="text-sm font-medium text-gray-700">同时导出PDF版本 (PDF转化需要服务器加载时间，请耐心等待)</label>
                        </div>

                        <!-- 提交按钮 -->
                        <div class="flex justify-center pt-4">
                            <button type="submit" id="exportBtn" class="fancy-button group" disabled>
                                <i class="fas fa-download mr-2 group-hover:animate-bounce"></i>
                                一键导出学号
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 右侧状态面板 -->
            <div class="md:col-span-3">
                <div class="bg-white p-6 side-panel rounded-lg shadow-md">
                    <h3 class="text-lg font-semibold text-gray-800 mb-5 flex items-center border-b pb-3">
                        <i class="fas fa-tasks text-blue-500 mr-2"></i>
                        处理状态
                    </h3>
                    
                    <div class="flex-grow">
                        <!-- 初始状态指示 -->
                        <div class="status-indicator pl-4 py-3 border-l-4 border-gray-300 bg-gray-50 rounded">
                            <div class="flex items-center">
                                <div class="w-3 h-3 bg-gray-400 rounded-full mr-2"></div>
                                <p class="text-sm font-medium text-gray-700">等待提交</p>
                            </div>
                            <p class="text-xs text-gray-500 mt-1 ml-5">请完成表单并点击导出按钮</p>
                        </div>

                        <!-- 处理状态提示 (包含进度条) -->
                        <div id="processStatus" class="hidden">
                            <div class="status-indicator active pl-4 py-3 border-l-4 border-blue-500 bg-blue-50 rounded">
                                <div class="flex items-center">
                                    <div class="w-3 h-3 bg-blue-500 rounded-full mr-2 pulse"></div>
                                    <p class="text-sm font-medium text-gray-700">处理进度</p>
                                </div>
                                
                                <div class="progress-container ml-5">
                                    <div class="progress-bar-wrapper">
                                        <div id="progressBar" class="progress-bar bg-blue-600" style="width: 0%"></div>
                                    </div>
                                    <div class="flex justify-between text-xs text-gray-500 mt-1">
                                        <span id="progressText">准备提交...</span>
                                        <span id="progressPercent">0%</span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="info-box info mt-4">
                                <div class="flex">
                                    <i class="fas fa-info-circle text-blue-600 mr-2 mt-0.5"></i>
                                    <div>
                                        <p class="text-sm text-gray-700">请求已提交，请在新窗口查看下载。</p>
                                        <p class="text-sm font-medium text-gray-800 mt-1">预期文件名: <span id="expectedFilename" class="text-blue-600"></span></p>
                                    </div>
                                </div>
                            </div>
                            <p class="text-xs text-gray-500 text-center mt-2">如果长时间未开始下载，请检查浏览器是否阻止了弹出窗口。</p>
                        </div>
                        
                        <!-- 新增: 导出完成后的消息区域 -->
                        <div id="downloadCompleteMessage" class="mt-4 hidden"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const uploadForm = document.getElementById('uploadForm');
            const fileInput = document.getElementById('fileUpload');
            const schoolNameInput = document.getElementById('schoolName');
            const exportBtn = document.getElementById('exportBtn');
            const fileInfoDiv = document.getElementById('fileInfo');
            const fileNameSpan = document.getElementById('fileName');
            const fileSizeSpan = document.getElementById('fileSize');
            const removeFileBtn = document.getElementById('removeFile');
            const fileErrorDiv = document.getElementById('fileError');
            const errorTextSpan = document.getElementById('errorText');
            const processStatusDiv = document.getElementById('processStatus');
            const progressBar = document.getElementById('progressBar');
            const progressText = document.getElementById('progressText');
            const progressPercent = document.getElementById('progressPercent');
            const expectedFilenameSpan = document.getElementById('expectedFilename');
            const fileDropArea = document.getElementById('fileDropArea');
            const downloadCompleteMessageDiv = document.getElementById('downloadCompleteMessage'); 
            const includePdfCheckbox = document.getElementById('includePdf'); 

            let progressInterval = null;
            let isProcessing = false; // Flag to prevent multiple submissions

            // --- Form Validation & Button State ---
            function validateForm() {
                if (isProcessing) return; // Don't change state while processing
                const fileSelected = fileInput.files.length > 0;
                const schoolNameEntered = schoolNameInput.value.trim() !== '';
                exportBtn.disabled = !(fileSelected && schoolNameEntered);
            }

            fileInput.addEventListener('change', validateForm);
            schoolNameInput.addEventListener('input', validateForm);

            // --- File Selection & Display ---
            function handleFileSelection(file) {
                 if (!file) {
                     resetFileInput(); // Ensure reset if no file
                     return;
                 }

                const validTypes = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
                const extension = file.name.split('.').pop().toLowerCase();
                const maxSizeMB = 10;

                if (file.size > maxSizeMB * 1024 * 1024) {
                    showError(`文件过大 (最大 ${maxSizeMB}MB)`);
                    resetFileInput();
                    return;
                }

                if (validTypes.includes(file.type) || ['xls', 'xlsx'].includes(extension)) {
                    fileNameSpan.textContent = file.name;
                    let size = file.size;
                    let sizeUnit = 'B';
                    if (size > 1024) { size = (size / 1024); sizeUnit = 'KB'; }
                    if (size > 1024) { size = (size / 1024); sizeUnit = 'MB'; }
                    fileSizeSpan.textContent = `(${size.toFixed(1)}${sizeUnit})`;

                    fileInfoDiv.classList.remove('hidden');
                    fileErrorDiv.classList.add('hidden');
                } else {
                    showError('文件格式无效 (需 .xlsx 或 .xls)');
                    resetFileInput();
                    return;
                }
                 validateForm();
            }

            function showError(message) {
                errorTextSpan.textContent = message;
                fileErrorDiv.classList.remove('hidden');
                fileInfoDiv.classList.add('hidden');
                
                // 在侧边栏显示错误信息
                downloadCompleteMessageDiv.innerHTML = `
                    <div class="info-box error">
                        <div class="flex">
                            <i class="fas fa-times-circle text-red-600 mr-2 mt-0.5"></i>
                            <div>
                                <p class="text-sm font-medium text-red-800">处理失败</p>
                                <p class="text-sm text-red-700">${message}</p>
                            </div>
                        </div>
                    </div>
                `;
                downloadCompleteMessageDiv.classList.remove('hidden');
                processStatusDiv.classList.add('hidden'); // Hide progress on error
                
                resetProcessingState(); // Reset button state etc.
            }

            function resetFileInput() {
                fileInput.value = '';
                fileInfoDiv.classList.add('hidden');
                fileErrorDiv.classList.add('hidden');
                downloadCompleteMessageDiv.classList.add('hidden'); // Hide complete message too
                 validateForm();
            }
            
             function resetProcessingState() {
                isProcessing = false;
                clearInterval(progressInterval);
                // Reset progress bar color
                progressBar.classList.remove('bg-green-500', 'bg-red-500');
                progressBar.classList.add('bg-blue-600');
                validateForm(); // Re-enable button if valid
             }

            fileInput.addEventListener('change', function(e) {
                handleFileSelection(e.target.files[0]);
            });

            removeFileBtn.addEventListener('click', function() {
                resetFileInput();
            });

             // --- Drag and Drop ---
             fileDropArea.addEventListener('dragover', (e) => {
                 e.preventDefault();
                 fileDropArea.classList.add('dragover');
             });

             fileDropArea.addEventListener('dragleave', () => {
                 fileDropArea.classList.remove('dragover');
             });

             fileDropArea.addEventListener('drop', (e) => {
                 e.preventDefault();
                 fileDropArea.classList.remove('dragover');
                 if (e.dataTransfer.files.length > 0) {
                     const file = e.dataTransfer.files[0];
                     const dataTransfer = new DataTransfer();
                     dataTransfer.items.add(file);
                     fileInput.files = dataTransfer.files;
                     handleFileSelection(file);
                 }
             });

             fileDropArea.addEventListener('click', (e) => {
                 if (e.target !== fileInput) {
                     fileInput.click();
                 }
             });

            // --- Simulated Progress Bar Logic ---
            function updateSimulatedProgress(percentage, text) {
                percentage = Math.min(percentage, 100); // Cap at 100
                progressBar.style.width = `${percentage}%`;
                progressPercent.textContent = `${Math.round(percentage)}%`;
                progressText.textContent = text;
            }

            function startSimulatedProgress() {
                clearInterval(progressInterval); 
                isProcessing = true;
                exportBtn.disabled = true; // Ensure button is disabled
                processStatusDiv.classList.remove('hidden');
                downloadCompleteMessageDiv.classList.add('hidden'); // Hide previous complete message
                progressBar.classList.remove('bg-green-500', 'bg-red-500'); // Reset color
                progressBar.classList.add('bg-blue-600');
                
                let currentProgress = 0;
                updateSimulatedProgress(0, '准备上传...');
                expectedFilenameSpan.textContent = `${schoolNameInput.value.trim() || '导出文件'}.zip`;

                // Phase 1: Simulate upload (fast)
                setTimeout(() => updateSimulatedProgress(15, '上传中...'), 100);
                setTimeout(() => updateSimulatedProgress(30, '上传中...'), 300);

                 // Phase 2: Simulate processing (slower, controlled by interval)
                 progressInterval = setInterval(() => {
                     currentProgress += Math.random() * 8 + 4; // Simulate uneven processing
                     if (currentProgress >= 85) { 
                         updateSimulatedProgress(85, '生成文件中...');
                         clearInterval(progressInterval); // Stop before reaching 95 here
                     } else {
                         updateSimulatedProgress(30 + currentProgress * 0.65, '服务器处理中...'); // Scale to 30-85 range
                     }
                 }, 500); 
            }
            
            function completeProgress(success, messageOrWarning = '') {
                 clearInterval(progressInterval); // Ensure interval is stopped
                 
                 if (success) {
                     updateSimulatedProgress(100, '处理完成');
                     progressBar.classList.remove('bg-blue-600');
                     progressBar.classList.add('bg-green-500'); 
                     
                     // Display success message in the dedicated div
                     downloadCompleteMessageDiv.innerHTML = `
                        <div class="info-box success">
                            <div class="flex">
                                <i class="fas fa-check-circle text-green-600 mr-2 mt-0.5"></i>
                                <div>
                                    <p class="text-sm font-medium text-green-800">导出成功!</p>
                                    <p class="text-sm text-green-700">文件已开始下载。 ${messageOrWarning}</p>
                                </div>
                            </div>
                        </div>
                     `;
                     downloadCompleteMessageDiv.classList.remove('hidden');
                 } else {
                      updateSimulatedProgress(100, '处理失败'); 
                      progressBar.classList.remove('bg-blue-600');
                      progressBar.classList.add('bg-red-500');
                      showError(messageOrWarning || '未知错误'); 
                 }
                  resetProcessingState();
             }

            // --- Form Submission using Fetch API ---
            uploadForm.addEventListener('submit', function(e) {
                e.preventDefault(); // 阻止表单默认提交行为
                
                if (isProcessing) return false;
                isProcessing = true;
                
                // 创建FormData对象
                const formData = new FormData(uploadForm);
                
                // 显示处理状态
                processStatusDiv.classList.remove('hidden');
                progressBar.style.width = '0%';
                progressText.textContent = '正在提交...';
                progressPercent.textContent = '0%';
                
                // 生成预期的文件名
                const schoolName = schoolNameInput.value.trim();
                expectedFilenameSpan.textContent = `${schoolName}.zip`;
                
                // 模拟进度（实际上是异步请求，无法获知真实进度）
                let progress = 0;
                progressInterval = setInterval(() => {
                    if (progress < 95) {
                        progress += Math.random() * 5;
                        progressBar.style.width = `${Math.min(progress, 95)}%`;
                        progressPercent.textContent = `${Math.round(Math.min(progress, 95))}%`;
                        
                        if (progress < 20) {
                            progressText.textContent = '正在解析上传文件...';
                        } else if (progress < 50) {
                            progressText.textContent = '正在处理数据...';
                        } else if (progress < 80) {
                            progressText.textContent = '正在生成文件...';
                        } else {
                            progressText.textContent = '准备下载...';
                        }
                    }
                }, 500);
                
                // 获取JWT Token并添加到请求头
                const token = sessionStorage.getItem('jwtToken');
                
                // 创建XMLHttpRequest对象
                const xhr = new XMLHttpRequest();
                xhr.open('POST', '/downloadExcel', true);
                
                // 如果有token则添加到请求头
                if (token) {
                    xhr.setRequestHeader('Authorization', `Bearer ${token}`);
                }
                
                // 设置响应类型为blob（二进制数据）
                xhr.responseType = 'blob';
                
                // 处理请求完成事件
                xhr.onload = function() {
                    clearInterval(progressInterval);
                    
                    if (xhr.status === 200) {
                        // 成功获取响应
                        progress = 100;
                        progressBar.style.width = '100%';
                        progressPercent.textContent = '100%';
                        progressText.textContent = '下载已开始';
                        progressBar.classList.remove('bg-blue-600');
                        progressBar.classList.add('bg-green-500');
                        
                        // 创建blob URL
                        const blob = xhr.response;
                        const url = URL.createObjectURL(blob);
                        
                        // 创建临时a标签并触发下载
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = schoolName + '.zip';
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        
                        // 检查超大班级提示
                        const oversizedClassesHeader = xhr.getResponseHeader('X-Oversized-Classes');
                        if (oversizedClassesHeader) {
                            // 处理超大班级信息
                            try {
                                const messages = oversizedClassesHeader.split('|').map(item => decodeURIComponent(item));
                                if (messages.length > 0) {
                                    // 显示超大班级警告
                                    let warningHTML = `
                                        <div class="info-box warning">
                                            <div class="flex">
                                                <i class="fas fa-exclamation-triangle text-yellow-600 mr-2 mt-0.5"></i>
                                                <div>
                                                    <p class="text-sm font-medium text-yellow-800">注意：以下班级学生人数超过容纳数量</p>
                                                    <ul class="mt-1 text-sm text-yellow-700 list-disc list-inside pl-1">`;
                                    
                                    messages.forEach(message => {
                                        warningHTML += `<li>${message}</li>`;
                                    });
                                    
                                    warningHTML += `
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>`;
                                    
                                    downloadCompleteMessageDiv.innerHTML = warningHTML;
                                    downloadCompleteMessageDiv.classList.remove('hidden');
                                }
                            } catch (e) {
                                console.error('解析超大班级信息失败:', e);
                            }
                        }
                        
                        // 重置处理状态
                        setTimeout(resetProcessingState, 3000);
                    } else if (xhr.status === 401) {
                        // 未授权，可能是token过期
                        progressBar.classList.remove('bg-blue-600');
                        progressBar.classList.add('bg-red-500');
                        progressText.textContent = '登录已失效，请重新登录';
                        
                        // 如果是blob响应，需要读取为文本以获取错误信息
                        const reader = new FileReader();
                        reader.onload = function() {
                            try {
                                const errorResponse = JSON.parse(reader.result);
                                const errorMessage = errorResponse.message || '登录已失效，请重新登录';
                                let errorTitle = '登录已失效';
                                let errorType = 'session_expired';
                                
                                // 根据错误类型设置不同的标题和类型
                                if (errorResponse.error === 'token_invalidated') {
                                    errorTitle = '账号已在其他设备登录';
                                    errorType = 'account_elsewhere';
                                } else if (errorResponse.error === 'token_expired') {
                                    errorTitle = '登录已过期';
                                    errorType = 'token_expired';
                                } else if (errorResponse.error === 'invalid_token') {
                                    errorTitle = '登录已失效';
                                    errorType = 'token_invalid';
                                }
                                
                                // 使用增强版认证弹窗
                                if (typeof window.showAuthModal === 'function') {
                                    window.showAuthModal(errorTitle, errorMessage, errorType);
                                }
                                // 兼容旧版提示
                                else if (typeof window.showMessage === 'function') {
                                    window.showMessage(errorTitle, errorMessage, 'error');
                                    
                                    // 设置短暂延迟后再重定向
                                    setTimeout(() => {
                                        // 清除会话存储
                                        if (typeof Api !== 'undefined' && typeof Api.clearAuthSession === 'function') {
                                            Api.clearAuthSession();
                                        } else {
                                            sessionStorage.removeItem('isLoggedIn');
                                            sessionStorage.removeItem('jwtToken');
                                            sessionStorage.removeItem('userFullName');
                                            sessionStorage.removeItem('userRole');
                                        }
                                        window.location.href = '/login.html';
                                    }, 3000);
                                } else {
                                    alert(errorMessage);
                                    window.location.href = '/login.html';
                                }
                            } catch (e) {
                                // 如果无法解析为JSON，使用通用错误消息
                                if (typeof window.showAuthModal === 'function') {
                                    window.showAuthModal('登录已失效', '您的登录状态已失效，请重新登录', 'session_expired');
                                } else {
                                    window.location.href = '/login.html';
                                }
                            }
                        };
                        reader.readAsText(xhr.response);
                    } else if (xhr.status === 503) {
                        // 服务器忙，有其他用户正在导出
                        progressBar.classList.remove('bg-blue-600');
                        progressBar.classList.add('bg-yellow-500');
                        progressText.textContent = '服务器忙';
                        
                        // 解析错误信息
                        const reader = new FileReader();
                        reader.onload = function() {
                            try {
                                const response = JSON.parse(reader.result);
                                const message = response.message || '系统正在为其他用户处理导出请求，请稍后再试';
                                
                                // 显示友好的等待提示
                                const warningHTML = `
                                    <div class="info-box warning">
                                        <div class="flex">
                                            <i class="fas fa-clock text-yellow-600 mr-2 mt-0.5"></i>
                                            <div>
                                                <p class="text-sm font-medium text-yellow-800">系统繁忙</p>
                                                <p class="text-sm text-yellow-700 mt-1">${message}</p>
                                                <button id="retryButton" class="mt-2 px-4 py-2 bg-yellow-100 hover:bg-yellow-200 text-yellow-800 rounded-md text-sm font-medium transition duration-200 border border-yellow-300">
                                                    稍后重试
                                                </button>
                                            </div>
                                        </div>
                                    </div>`;
                                
                                downloadCompleteMessageDiv.innerHTML = warningHTML;
                                downloadCompleteMessageDiv.classList.remove('hidden');
                                
                                // 添加重试按钮的点击事件
                                document.getElementById('retryButton').addEventListener('click', function() {
                                    // 隐藏警告消息
                                    downloadCompleteMessageDiv.classList.add('hidden');
                                    // 重置处理状态
                                    resetProcessingState();
                                });
                                
                            } catch (e) {
                                // 解析失败，显示通用消息
                                if (typeof window.showMessage === 'function') {
                                    window.showMessage('系统繁忙', '系统正在为其他用户处理导出请求，请稍后再试', 'warning');
                                } else {
                                    alert('系统正在为其他用户处理导出请求，请稍后再试');
                                }
                                setTimeout(resetProcessingState, 3000);
                            }
                        };
                        reader.readAsText(xhr.response);
                    } else {
                        // 其他错误
                        progressBar.classList.remove('bg-blue-600');
                        progressBar.classList.add('bg-red-500');
                        progressText.textContent = '处理失败';
                        
                        // 显示错误消息
                        const reader = new FileReader();
                        reader.onload = function() {
                            try {
                                let errorMessage = reader.result;
                                try {
                                    const errorObj = JSON.parse(reader.result);
                                    errorMessage = errorObj.message || errorObj.error || '处理失败，请重试';
                                } catch (e) {
                                    // 如果不是JSON格式，使用原始文本
                                }
                                
                                if (typeof window.showMessage === 'function') {
                                    window.showMessage('处理失败', errorMessage, 'error');
                                } else {
                                    alert('处理失败: ' + errorMessage);
                                }
                            } catch (e) {
                                alert('处理失败，请重试');
                            }
                            setTimeout(resetProcessingState, 3000);
                        };
                        reader.readAsText(xhr.response);
                    }
                };
                
                // 处理请求错误事件
                xhr.onerror = function() {
                    clearInterval(progressInterval);
                    progressBar.classList.remove('bg-blue-600');
                    progressBar.classList.add('bg-red-500');
                    progressText.textContent = '网络错误';
                    
                    // 在侧边栏显示错误信息
                    downloadCompleteMessageDiv.innerHTML = `
                        <div class="info-box error">
                            <div class="flex">
                                <i class="fas fa-wifi-slash text-red-600 mr-2 mt-0.5"></i>
                                <div>
                                    <p class="text-sm font-medium text-red-800">网络错误</p>
                                    <p class="text-sm text-red-700">请求失败，请检查您的网络连接</p>
                                </div>
                            </div>
                        </div>
                    `;
                    downloadCompleteMessageDiv.classList.remove('hidden');
                    
                    if (typeof window.showMessage === 'function') {
                        window.showMessage('网络错误', '请求失败，请检查您的网络连接', 'error');
                    } else {
                        alert('网络错误，请检查您的网络连接');
                    }
                    
                    setTimeout(resetProcessingState, 3000);
                };
                
                // 发送请求
                xhr.send(formData);
                
                return false;
            });

            // Initial validation check
            validateForm();
        });
    </script>

    <!-- 自定义消息提示弹窗 -->
    <div id="messageModal" class="fixed inset-0 flex items-center justify-center z-50 hidden">
        <div class="absolute inset-0 bg-black opacity-50"></div>
        <div class="bg-white rounded-lg p-6 max-w-sm w-full mx-4 relative z-10 animate-fade-in">
            <div class="flex items-center mb-4">
                <div id="messageIcon" class="flex-shrink-0 w-10 h-10 flex items-center justify-center rounded-full mr-4">
                    <i class="fas fa-exclamation-circle text-2xl"></i>
                </div>
                <h3 id="messageTitle" class="text-lg font-bold">提示</h3>
            </div>
            <p id="messageContent" class="text-gray-700 mb-6">提示内容</p>
            <div class="flex justify-end">
                <button id="messageCloseBtn" 
                    class="py-2 px-6 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-200">
                    确定
                </button>
            </div>
        </div>
    </div>

    <!-- 增强版认证状态弹窗 -->
    <div id="authStatusModal" class="fixed inset-0 flex items-center justify-center z-50 hidden">
        <div class="absolute inset-0 bg-black bg-opacity-70"></div>
        <div class="bg-white rounded-xl shadow-2xl p-8 max-w-md w-full mx-4 relative z-10 transform transition-all duration-300 scale-100 opacity-100">
            <div class="text-center mb-6">
                <div id="authStatusIcon" class="inline-flex items-center justify-center w-20 h-20 rounded-full mx-auto mb-4"></div>
                <h3 id="authStatusTitle" class="text-2xl font-bold text-gray-800 mb-1">登录状态</h3>
                <p id="authStatusContent" class="text-gray-600">状态信息</p>
            </div>
            <div class="pt-2 border-t border-gray-200">
                <div class="flex justify-center mt-4">
                    <button id="authStatusLoginBtn" class="flex items-center justify-center px-6 py-3 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition duration-200 shadow-md hover:shadow-lg w-full">
                        <i class="fas fa-sign-in-alt mr-2"></i>
                        重新登录
                    </button>
                </div>
                <p class="text-center text-gray-500 text-sm mt-3" id="authRedirectTimer">5秒后自动跳转至登录页面...</p>
            </div>
        </div>
    </div>

    <script>
        // 显示自定义消息弹窗
        function showMessage(title, content, type = 'info') {
            const modal = document.getElementById('messageModal');
            const titleEl = document.getElementById('messageTitle');
            const contentEl = document.getElementById('messageContent');
            const iconEl = document.getElementById('messageIcon');
            const closeBtn = document.getElementById('messageCloseBtn');
            
            titleEl.textContent = title;
            contentEl.textContent = content;
            
            // 根据消息类型设置图标和颜色
            switch(type) {
                case 'success':
                    iconEl.className = 'flex-shrink-0 w-10 h-10 flex items-center justify-center rounded-full mr-4 bg-green-100';
                    iconEl.innerHTML = '<i class="fas fa-check-circle text-2xl text-green-600"></i>';
                    break;
                case 'warning':
                    iconEl.className = 'flex-shrink-0 w-10 h-10 flex items-center justify-center rounded-full mr-4 bg-yellow-100';
                    iconEl.innerHTML = '<i class="fas fa-exclamation-triangle text-2xl text-yellow-600"></i>';
                    break;
                case 'error':
                    iconEl.className = 'flex-shrink-0 w-10 h-10 flex items-center justify-center rounded-full mr-4 bg-red-100';
                    iconEl.innerHTML = '<i class="fas fa-times-circle text-2xl text-red-600"></i>';
                    break;
                default: // info
                    iconEl.className = 'flex-shrink-0 w-10 h-10 flex items-center justify-center rounded-full mr-4 bg-blue-100';
                    iconEl.innerHTML = '<i class="fas fa-info-circle text-2xl text-blue-600"></i>';
            }
            
            // 显示弹窗
            modal.classList.remove('hidden');
            
            // 点击关闭按钮
            closeBtn.onclick = () => {
                modal.classList.add('hidden');
            };
            
            // 点击蒙层也关闭
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    modal.classList.add('hidden');
                }
            });
        }
        
        // 显示增强版认证状态弹窗
        function showAuthModal(title, message, errorType = 'session_expired') {
            const modal = document.getElementById('authStatusModal');
            const titleEl = document.getElementById('authStatusTitle');
            const contentEl = document.getElementById('authStatusContent');
            const iconEl = document.getElementById('authStatusIcon');
            const loginBtn = document.getElementById('authStatusLoginBtn');
            const timerEl = document.getElementById('authRedirectTimer');
            
            // 设置弹窗内容
            titleEl.textContent = title;
            contentEl.textContent = message;
            
            // 根据错误类型设置不同的图标和样式
            switch(errorType) {
                case 'account_elsewhere':
                    iconEl.className = 'inline-flex items-center justify-center w-20 h-20 rounded-full mx-auto mb-4 bg-yellow-100';
                    iconEl.innerHTML = '<i class="fas fa-user-lock text-4xl text-yellow-600"></i>';
                    break;
                case 'token_expired':
                    iconEl.className = 'inline-flex items-center justify-center w-20 h-20 rounded-full mx-auto mb-4 bg-blue-100';
                    iconEl.innerHTML = '<i class="fas fa-hourglass-end text-4xl text-blue-600"></i>';
                    break;
                case 'token_invalid':
                    iconEl.className = 'inline-flex items-center justify-center w-20 h-20 rounded-full mx-auto mb-4 bg-red-100';
                    iconEl.innerHTML = '<i class="fas fa-exclamation-triangle text-4xl text-red-600"></i>';
                    break;
                default:
                    iconEl.className = 'inline-flex items-center justify-center w-20 h-20 rounded-full mx-auto mb-4 bg-red-100';
                    iconEl.innerHTML = '<i class="fas fa-times-circle text-4xl text-red-600"></i>';
            }
            
            // 显示弹窗
            modal.classList.remove('hidden');
            
            // 添加动画效果
            const modalContent = modal.querySelector('div:nth-child(2)');
            modalContent.classList.add('scale-100', 'opacity-100');
            setTimeout(() => {
                modalContent.classList.remove('scale-95', 'opacity-0');
            }, 10);
            
            // 设置倒计时
            let countdown = 5;
            const updateTimer = () => {
                timerEl.textContent = `${countdown}秒后自动跳转至登录页面...`;
                if (countdown <= 0) {
                    clearInterval(timer);
                    // 清除会话存储
                    Api.clearAuthSession();
                    // 跳转到登录页
                    window.location.href = '/login.html';
                }
                countdown--;
            };
            
            // 开始倒计时
            updateTimer();
            const timer = setInterval(updateTimer, 1000);
            
            // 点击登录按钮
            loginBtn.onclick = () => {
                clearInterval(timer);
                // 清除会话存储
                Api.clearAuthSession();
                // 跳转到登录页
                window.location.href = '/login.html';
            };
        }
        
        // 暴露给window以便API.js可以调用
        window.showMessage = showMessage;
        window.showAuthModal = showAuthModal;
    </script>
</body>
</html>